package com.semidata.trp.business.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.SqlRunner;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SessionUtils {
    private static SqlSessionFactory sessionFactory = null;
    static {
        String resource = "conf/mybatis-business.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sessionFactory = new SqlSessionFactoryBuilder().build(new InputStreamReader(inputStream));
    }

    // 为了灵活获取session
    public static SqlSessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static SqlSession getSession() {
        return sessionFactory.openSession();
    }

    public static void close(SqlSession session) {
        
        if (session != null) {
            session.close();
        }
    }
    
    public static void executeSql(String... sqls) {
        SqlSession session = SessionUtils.getSession();
        SqlRunner runner = new SqlRunner(session.getConnection());
        try {
            runner.run("start transaction");
            for (String sql : sqls)
                runner.run(sql);
            runner.run("commit");
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                runner.run("rollback");
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            session.close();
        }
    }
    
    public static void main(String[] args) {
        executeSql("insert into trp_area (name, code) values('test3', 'test3')", "insert into trp_area (name, code) values('test4', 'test4')");        
    }
}
